package com.xiaoxin.yixinai._frame.base;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
@Aspect
public class ControllerAdvice {

	// private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private HttpServletRequest request;
	
	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	public void initCtx(){}
	@Before("initCtx()")
	public void beforeInitCtx(){
		request.setAttribute("ctx", request.getContextPath());
	}
	
	@Pointcut("@annotation(com.xiaoxin.yixinai._frame.base.ModuleCode)")
	public void initModule(){}
	@Around("initModule()")
	public Object aoundInitModule(ProceedingJoinPoint jointPoint) throws Throwable{
		Signature sig = jointPoint.getSignature();
	    MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = jointPoint.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
		
		ModuleCode mc = currentMethod.getAnnotation(ModuleCode.class);
		if(mc!=null){
			String value = mc.value();
			String pValue = mc.pValue();
			if(StringUtils.isEmpty(pValue)){
				pValue = value;
			}
			request.getSession().setAttribute("moduleCode", value);
			request.getSession().setAttribute("pModuleCode", pValue);
		}
		return jointPoint.proceed();
	}
}
